package log

import (
	"os"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

type Option = lumberjack.Logger

func NewZapLogger(o *Option) *zap.SugaredLogger {
	dir := filepath.Dir(o.Filename)
	if err := os.MkdirAll(dir, 0766); err != nil {
		panic(err)
	}
	writer := zapcore.NewMultiWriteSyncer(zapcore.AddSync(o), zapcore.AddSync(os.Stdout))

	encfg := zap.NewProductionEncoderConfig()
	encfg.EncodeTime = zapcore.ISO8601TimeEncoder
	encfg.EncodeLevel = zapcore.CapitalLevelEncoder

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encfg),
		writer,
		zapcore.DebugLevel,
	)
	logger := zap.New(core, zap.AddCaller())
	return logger.Sugar()
}

var ZapLogger = NewZapLogger(&Option{
	Filename:   "logs/log.txt",
	MaxSize:    20,
	MaxAge:     30,
	MaxBackups: 5,
	Compress:   false,
})

func ZapGinLogger(l *zap.SugaredLogger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		c.Next()
		cost := time.Since(start)
		l.Infof(" %3d | %13v | %15s |%-7s %s", c.Writer.Status(), cost, c.ClientIP(), c.Request.Method, path)
	}
}
